package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.intercepror.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;


    //添加联系人
    public void contacts(Long userId) {
        //1.将好友数据存入到mongodb
        Long crrUserId = UserHolder.getUserId();
        friendApi.save(crrUserId, userId);
        //2.将好友数据写入到环信
        huanXinTemplate.addContact("hx" + crrUserId, "hx" + userId);//添加好友的环信用户名
    }

    //查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.查询用户的好友列表
        List<Friend> list = friendApi.findByUserId(page,pagesize,userId);
        //3.判断这个列表是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //4.根据好友id获取用户好友的信息UserInfo
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //获取好友的id
            Long friendId = friend.getFriendId();
            //查询好友的信息
            UserInfo userInfo = map.get(friendId);
            //5.构造出vo对象
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        //6.构造返回值
        return new PageResult(page, pagesize, 0l, vos);
    }

    //根据环信用户名，查询用户信息
    public UserInfoVo findByHuanxin(String huanxinId) {
        //通过对环信名的截取获取用户的id
        String s = huanxinId.substring(2);
        Long userId = Long.valueOf(s);
        UserInfo userInfo = userInfoApi.findById(userId);
        //转换vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);//同名同类型转换
        if (userInfo.getAge() != null) {//类型不同进行判断单独转换
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }
}
